package ltd.newbee.cloud.web;

import ltd.newbee.cloud.config.RestTemplateConfig;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Auther: tangyushan
 * @Date: 2024/5/17 - 05 - 17 - 18:09
 * @Description: ltd.newbee.cloud.web
 * @version: 1.0
 */
@RestController
public class ConsumerController {

    private final String SERVICE_URL = "http://localhost:8081";
//    private final String SERVICE_URL = "http://localhost:8082";


    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/restTemplateTest")
    public String restTemplateTest() {
        System.out.println(restTemplate.getForObject(SERVICE_URL + "/hello", String.class));
        ArrayList arrayList = new ArrayList();
        List list = Collections.synchronizedList(arrayList);
        return "请求成功";
    }

    /**
     * 使用HttpClient发起GET请求的测试方法。
     * 该方法会向指定的服务URL发送GET请求，并打印响应内容。
     *
     * @return 返回一个字符串表示请求是否成功。
     * @throws IOException 如果发生I/O错误。
     */
    @GetMapping("/httpClientTest")
    public String httpClientTest() throws IOException {
        // 创建一个CloseableHttpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 构建GET请求的URL
        HttpGet httpGet = new HttpGet(SERVICE_URL + "/hello");
        CloseableHttpResponse response = null;

        try {
            // 执行HTTP GET请求
            response = httpClient.execute(httpGet);

            // 检查响应状态码
            if(response.getStatusLine().getStatusCode() == 200){
                // 读取并打印响应内容
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
            }
        } finally {
            // 释放资源
            if(response != null){
                response.close();
            }
            httpClient.close();
        }

        return "请求成功";
    }
}
